<?php

/**
 * <p>通过摇电视与摇周边红包的总结</p>
 * 大致上可以总结出以下步骤
 * 1.
 * @author czb
 *
 */
class zbController extends  appController{
	
	public function zbhbActive()
	{
		$page=isset($_REQUEST['page'])?intval($_REQUEST['page']):1;
		$zbhb_list=Model('zb')->getZbhbActiveList($page);
		$this->assign('luckyDraw_list',$zbhb_list['data']);
		$this->assign('luckyDraw_list_page',$zbhb_list['pagelink']);
		$this->assign('count',$zbhb_list['count']);
		$this->display('zbhb_active_list.html');
	}
	
	public function addZbhbActive()
	{
		if(isset($_GET['id']))
		{
			$info = Model('zb')->getZbhbActive($_GET['id']);
			$this->assign('info', $info);
			$this->display("zbhb_active_edit.html");
		}
		else
		{
			$this->display("zbhb_active_edit.html");
		}
	}
	
	public function editZbhbActive()
	{
		$result = array('error'=>0,'content'=>'编辑成功');
		$info['title'] = isset($_POST['title'])?$_POST['title']:"";
		if($info['title']=="")
		{
			$result = array('error'=>1,'content'=>'活动名称不可为空');
			$this->showMsg($result);
		}
		$info['descShow'] = isset($_POST['descShow'])?$_POST['descShow']:"";
		if($info['descShow']=="")
		{
			$result = array('error'=>1,'content'=>'活动描述不可为空');
			$this->showMsg($result);
		}
		$info['begin_time'] = isset($_POST['begin_time'])?strtotime($_POST['begin_time']):yf_time();
		$info['expire_time'] = isset($_POST['expire_time'])?strtotime($_POST['expire_time']):yf_time()+(3*24*60*60);
		$info['onoff'] = isset($_POST['onoff'])?$_POST['onoff']:1;
		$info['status'] = 2;
		if(!empty($_POST['id']))
		{//编辑
			Model('zb')->update($info,array('table'=>'zbhb_info','id'=>$_POST['id']));
		}
		else
		{//新增
			Model('zb')->insert($info,'zbhb_info');
		}
		$this->showMsg($result);
	}
	/**
	 * 先录入活动
	 */
	public function entering()
	{
		$result = array('error'=>0,'content'=>'活动已启用，请录入红包至该活动中！');
		$id = isset($_POST['id'])?$_POST['id']:"";
		$m = Model('zb');
		$info = $m->getZbhbActive($id);
		if($info['onoff']==0){
			$result = array('error'=>1,'content'=>'抽奖开关请设为开');
			$this->showMsg($result);
		}
		$accessToken = $m->getAccessToken();
		$url = "https://api.weixin.qq.com/shakearound/lottery/addlotteryinfo?access_token=".$accessToken."&use_template=2";
		$path = ROOT_PATH."Admin/Config/ZB.json";
		$data = json_decode(file_get_contents($path), true);
		$post_data=array(
				'title'=>iconv('gb2312','utf-8',$info['title']),
				'desc'=>iconv('gb2312','utf-8',$info['descShow']),
				'onoff'=>$info['onoff'],
				'begin_time'=>$info['begin_time'],
				'expire_time'=>$info['expire_time'],
				'sponsor_appid'=>$data['wxappid'],
				'total'=>$info['total'],
				'jump_url'=>"http://g4.airefp.com/ws/index.php?g=mobile&m=newYear&a=indexZB",
				'key'=>$data['key'],
		);
		$res = json_decode($this->post_it($url,json_encode($post_data)),true);
		if($res['errcode']===0){
			$arr['lottery_id'] = $res['lottery_id'];
			$arr['status'] = 3;
			$m->update($arr,array("table"=>"zbhb_info","id"=>$id));
		}else{
			$result['error'] = 1;
			$result['content']=$res['errmsg'];
		}
		$this->showMsg($result);
	}
	
	public function setprize(){
		$result = array('error'=>0,'content'=>'红包已录入！');
		$id = isset($_POST['id'])?$_POST['id']:"";
		$m = Model('zb');
		$info = $m->getZbhbNotPull($id);
		$accessToken = $m->getAccessToken();
		$path = ROOT_PATH."Admin/Config/ZB.json";
		$data = json_decode(file_get_contents($path), true);
		if($info['total'])
		{
			if($info['nototal'])
			{
				$enteringurl = "https://api.weixin.qq.com/shakearound/lottery/setprizebucket?access_token=".$accessToken;
				$resu = $this->entering2($enteringurl, $id, $data,$info['lottery_id']);
				if($resu['errcode']===0)
				{
					if($resu["ticket_error_length"]!=0)
					{
						$result['content']="有".$resu["ticket_error_length"]."个红包无效，可能原因是红包失效";
					}
				}
				else
				{
					$result['error'] = 1;
					$result['content']=$resu['errmsg'];
				}
			}
			else
			{
				$arr['status'] = 1;
				$m->update($arr,array("table"=>"zbhb_info","id"=>$id));
				$result['error'] = 2;
				$result['content']="红包已全部提交";
			}
		}
		else
		{
			$result['error'] = 1;
			$result['content']="无红包数量";
		}
		$this->showMsg($result);
	
	}
	
	public function entering2($url,$id,$data,$lottery_id){
		$res['ticket_err_list'] = 0;
		$m=Model('zb');
		$hongbao = $m->getZbhbListTicketNoPush($id);
		$arr = array(
				"lottery_id"=>$lottery_id,
				"mchid"=>$data['mch_id'],
				"sponsor_appid"=>$data['wxappid'],
				"prize_info_list"=>$hongbao['list']
		);
		$res = json_decode($this->post_it($url,json_encode($arr)),true);
		if($res['errcode']===0){
			$m->updateHongbaoStatus($hongbao['idlist'],2);
		}
		$res['ticket_error_length'] = count($res['ticket_err_list']);
		return $res;
	}
	
	/*************************************************红包信息*************************************/
	public function zbhbHongbao()
	{
		$page=isset($_REQUEST['page'])?intval($_REQUEST['page']):1;
		$id = $_GET['id'];
		$hongbao_list=Model('zb')->get_hongbao_list($page,$id);
		$this->assign('hongbao_list',$hongbao_list['data']);
		$this->assign('hongbao_list_page',$hongbao_list['pagelink']);
		$this->assign('count',$hongbao_list['count']);
		$this->assign("id", $id);
		$info = Model('zb')->getZbhbActive($id);
		$this->assign("status", $info['status']);
		$this->display('zbhb_hongbao_list.html');
	}
	
	public function addZbhbHongbao()
	{
		$id = $_GET['id'];
		$this->assign("id", $id);
		$this->display("zbhb_hongbao_edit.html");
	}
	
	public function insertZbhbHongbao()
	{
		$result = array('error' => 0,"content"=>"红包成功预下单");
		$m = Model('zb');
		$info['hb_type'] = isset($_POST['hb_type'])?intval($_POST['hb_type']):2;
		$info['total_amount'] = isset($_POST['total_amount'])?$_POST['total_amount']:0;
		if($info['total_amount']==0)
		{
			$result = array('error'=>1,'content'=>'金额不可为空');
			$this->showMsg($result);
		}
		$info['total_num'] = isset($_POST['total_num'])?intval($_POST['total_num']):1;
		$info['wishing'] = yf_empty($_POST['wishing'],"祝福语不可为空");
		$info['act_name'] = yf_empty($_POST['act_name'],"祝福语不可为空");
		$info['remark'] = isset($_POST['remark'])?$_POST['remark']:"红包-".$info['act_name'];
		$info['lid'] = $_POST['lid'];
		$hid = $m->insert($info,'zbhb_hongbao');
		if($info['hb_type']==1)
		{
			$info['hb_type']="GROUP";
		}
		else
		{
			$info['hb_type']="NORMAL";
		}
		$info['id'] = $hid;
		//发送红包预下单请求
		$res = $this->sendRedPack($info);
		if($res['return_code']=='SUCCESS'&&$res['result_code']=='SUCCESS'){
			$arr['sp_ticket'] = $res['sp_ticket'];
			$arr['detail_id'] = $res['detail_id'];
			$arr['mch_billno'] = $res['mch_billno'];
			$m->update($arr,array("table"=>"zbhb_hongbao","id"=>$hid));
		}else{
			$m->del(array("table"=>"zbhb_hongbao","id"=>$hid));
			$result['error'] = 1;
			$result['content']="错误原因:".$res['return_msg']."--".$res['err_code_des'].";";
		}
	
		$this->showMsg($result);
	}
	
	public function sendRedPack($info)
	{
		$m = Model('zb');
		$path = ROOT_PATH."Admin/Config/ZB.json";
		$data = json_decode(file_get_contents($path), true);
		//请求数据
		$mch_billno = $m->get_mch_billno($data['mch_id'],rand_match(10),yf_time());
		
		$sendData = array(
				'nonce_str' => hy_rand(20),
				'mch_billno' => $mch_billno,
				'mch_id' =>$data['mch_id'],
				'wxappid' =>$data['wxappid'],
				'send_name' => '新闻日日睇',//发送者名称
				'hb_type'=>$info['hb_type'],//红包类型
				'total_amount' =>$info['total_amount']*100,//红包总金额，已分为单位
				'total_num' =>$info['total_num'],
				'amt_type'=>"ALL_RAND",//红包金额设置方式 ALL_RAND—全部随机
				'wishing'=>$info['wishing']?$info['wishing']:'恭喜发财，大吉大利',//祝福语
				'act_name'=>$info['act_name']?$info['act_name']:'微信红包',//活动名称
				'remark'=>$info['remark']?$info['remark']:'发红包',//备注
				'auth_appid'=>$data['auth_appid']?$data['auth_appid']:'wxbf42bd79c4391863',//授权商户APPID
				'auth_mchid'=>$data['auth_mchid']?$data['auth_mchid']:'1000052601',//授权商户号
				'risk_cntl'=>'NORMAL',//风控设置
		);
		//签名步骤一：按字典序排序参数
		ksort($sendData);
		$string = $this->ToUrlParams($sendData);
		//签名步骤二：在string后加入KEY
		$string = $string . "&key=".$data['key'];
		//签名步骤三：MD5加密
		$string = md5($string);
		//签名步骤四：所有字符转为大写
		$sign = strtoupper($string);
		$sendData['sign'] = $sign;
		
		$xml = "<xml>";
		foreach ($sendData as $key=>$val)
		{
			$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
		}
		$xml.="</xml>";
		$url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/hbpreorder";
		$result=$this->post_it_with_ssl($url, $xml);
		if($result){
			$result=(array)simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
		}else{
			return $result;
		}
		return $result;
	}
	
	private function post_it_with_ssl($url, $str, $second=30,$aHeader=array()){
		$ch = curl_init();
		//超时时间
		curl_setopt($ch,CURLOPT_TIMEOUT,$second);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
		//这里设置代理，如果有的话
		//curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
		//curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
		//以下两种方式需选择一种
		//第一种方法，cert 与 key 分别属于两个.pem文件
		//默认格式为PEM，可以注释
		//curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
		curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/Config/cert.pem');
		//默认格式为PEM，可以注释
		//curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
		curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/Config/key.pem');
		//第二种方式，两个文件合成一个.pem文件
		// 		curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');
	
		curl_setopt($ch,CURLOPT_POST, 1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$str);
		$data = curl_exec($ch);
		if($data){
			curl_close($ch);
			return $data;
		}
		else {
			$error = curl_errno($ch);
			//echo "call faild, errorCode:$error\n";
			curl_close($ch);
			return false;
		}
	}
	
	public function delZbhbRepeat()
	{
		$lid = intval($_GET['lid']);
		Model('zb')->delZbhbRepeat($lid);
		$res['error'] = 0;
		$this->showMsg($res);
	}
	
	public function closeHongbao()
	{
		$lottery_id = $_POST['id'];
		$m = Model('zb');
		$accessToken = $m->getAccessToken();
		$info = Model('zb')->getZbhbActive($lottery_id);
		if($info['onoff']==1)
		{
			$onoff = 0;
		}else{
			$onoff = 1;
		}
		$id = $info['lottery_id'];
		$url=":https://api.weixin.qq.com/shakearound/lottery/setlotteryswitch?access_token=$accessToken&lottery_id=$id&onoff=$onoff";
		$result = json_decode($this->get_it($url),true);
		if($result['errcode']==0)
		{
			Model('zb')->update(array('onoff'=>$onoff),array("table"=>"zbhb_info","id"=>$lottery_id));
		}
		print_r(json_encode($result));
	}
	
}